package git.soulbgm.controller;

import git.soulbgm.utils.CacheUtil;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 缓存控制器
 *
 * @author SoulBGM
 * @date 2022/03/30 10:56
 */
@RestController
@RequestMapping("cache")
public class CacheController {

    private final CacheUtil cache;

    public CacheController(CacheUtil cache) {
        this.cache = cache;
    }

    @GetMapping("put")
    public String put(String cacheName, String key, String value) {
        cache.put(cacheName, key, value);
        return "success";
    }

    @GetMapping("get")
    public Object get(String cacheName, String key) {
        final Object obj = cache.get(cacheName, key);
        if (obj instanceof SimpleValueWrapper) {
            return ((SimpleValueWrapper) obj).get();
        }
        return obj;
    }

    @GetMapping("remove")
    public String remove(String cacheName, String key) {
        cache.remove(cacheName, key);
        return "success";
    }

    @GetMapping("removeAll")
    public String removeAll(String cacheName) {
        cache.removeAll(cacheName);
        return "success";
    }

    @GetMapping("getCacheNames")
    public String getCacheNames() {
        return String.join(",", cache.getCacheNames());
    }

}
